"""
图的抽象信息，只作为图的描述，与具体图的内容无关
"""
import ast
import json
from flask import Blueprint, request, jsonify
import server.database.sql.graph.describe as db
from server.utils.formatData import format_data
from server.utils.handleFile import save_base64_as_file, file_to_base64, del_directory

route_graph_describe = Blueprint('graph/describe', __name__)


# 信息获取
# 获取节点和边等信息
@route_graph_describe.route('', methods=['GET'])
def get_describe():
    if request.method == 'GET':
        gid = request.args.get('gid')
        data = db.get_describe(gid)

        if data is None:
            return 'null'

        # 调整格式
        data = format_data(data)
        if data['otype'] == 1:
            data['time'] = data['utime']
        elif data['otype'] == 2:
            data['time'] = data['etime']
        elif data['otype'] == 0:
            data['time'] = data['ctime']
        # 处理图片
        if data['img'] is None or len(data['img']) == 0:
            data['img'] = []
        else:
            i = 0
            for file_path in data['img']:
                base64 = file_to_base64(file_path, 1)
                data['img'][i] = base64
                i += 1

        return jsonify(data)


# 内容更新
@route_graph_describe.route('/update', methods=['POST'])
def update_describe():
    if request.method == 'POST':
        gid = request.form.get('gid')
        name = request.form.get('name')
        note = request.form.get('note')
        uid = request.form.get('uid')
        img = request.form.get('img')
        ctime = request.form.get('ctime')
        utime = request.form.get('utime')
        etime = request.form.get('etime')
        otype = request.form.get('otype')

        if img is not None:
            img = ast.literal_eval(img)
            if len(img) > 0:
                i = 0
                for base64 in img:
                    file_path = uid + '/' + gid + '/'
                    img_name = 'describe_img' + str(i) + '.jpg'
                    save_base64_as_file(base64, file_path, img_name)
                    img[i] = file_path + img_name
                    i += 1
            img = json.dumps(img)
        res = str(db.update_describe(gid, name, note, uid, img, ctime, utime, etime, otype))

        return res